package com.sk.tools.excel.reader;

import com.sk.tools.excel.meta.model.ExcelMeta;
import com.sk.tools.excel.exception.EmptyExcelException;
import com.sk.tools.excel.exception.EmptySheetException;
import com.sk.tools.excel.handler.RecordHandler;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;

public class PoiDomReader implements Reader {

    Logger logger = LoggerFactory.getLogger(PoiDomReader.class);
    private XSSFWorkbook workbook;

    @Override
    public void read(InputStream in, RecordHandler handler, ExcelMeta excelConfigMeta) {
        try {
            workbook = new XSSFWorkbook(in);
            if(excelConfigMeta == null){
                logger.warn("没有提供excel文件的元信息配置，默认全部解析");
                autoResolveExcel();
            }

            int allSheetNum = workbook.getNumberOfSheets();
            if(allSheetNum < 1){
                throw new EmptyExcelException();
            }


            
        } catch (IOException e) {
            logger.error("excel文件解析错误");
            e.printStackTrace();
        }
    }

    private void autoResolveExcel(){
        if(workbook == null) throw new EmptyExcelException();
        int sheetCount = workbook.getNumberOfSheets();
        if(sheetCount < 1){
            throw new EmptyExcelException();
        }
        for (int i = 0; i < sheetCount; i++) {
            Sheet sheet = workbook.getSheetAt(i);

            autoResolveSheet(sheet);
            
        }
    }

    private void autoResolveSheet(Sheet sheet){

        int rowCount = sheet.getPhysicalNumberOfRows();
        if(rowCount == 0){
            throw new EmptySheetException(sheet.getSheetName() + " has no data");
        }

    }
}
